﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Sunny.Entity;
using Sunny.Model.RequestParam;

namespace Sunny.Service
{
    public class OperateLogService
    {
        private readonly SunnyContext _sunnyContext;

        public OperateLogService(SunnyContext sunnyContext)
        {
            _sunnyContext = sunnyContext;
        }
        
        public void Add(SysOperLog sysOperLog)
        {
            _sunnyContext.SysOperLogs.Add(sysOperLog);
            _sunnyContext.SaveChanges();
        }

        public async Task<(List<SysOperLog>, int)> List(OperateLogListParam param)
        {
            var logs = _sunnyContext.SysOperLogs.AsQueryable();
            if(!string.IsNullOrEmpty(param.Title))
            {
                logs = logs.Where(t=>t.Title.Contains(param.Title));
            }
            if(!string.IsNullOrEmpty(param.BusinessType))
            {
                logs = logs.Where(t=>t.BusinessType == int.Parse(param.BusinessType));
            }
            if(!string.IsNullOrEmpty(param.OperName))
            {
                logs = logs.Where(t=>t.OperName.Contains(param.OperName));
            }
            if(!string.IsNullOrEmpty(param.Status))
            {
                logs = logs.Where(t=>t.Status == param.Status);
            }
            if(param.CreateTime is {Length: 2})
            {
                logs = logs.Where(t=>t.OperTime>= param.CreateTime[0] && t.OperTime<= param.CreateTime[1]);
            }
            int total = await logs.CountAsync();
            var logList = await logs.OrderByDescending(t=>t.OperTime).Skip((param.PageNum-1)*param.PageSize).Take(param.PageSize).ToListAsync();
            return  (logList,total);
        }

        public async Task BatchDelete(string logIds)
        {
            var strLogIds = logIds.Split(",");
            var lIds = Array.ConvertAll(strLogIds,long.Parse);
            var sysOperLogs = _sunnyContext.SysOperLogs.Where(t=>lIds.Contains(t.OperId));
            _sunnyContext.SysOperLogs.RemoveRange(sysOperLogs);
            await _sunnyContext.SaveChangesAsync();
        }

        public async Task DeleteAll()
        {
            var sysOperLogs = _sunnyContext.SysOperLogs.AsQueryable();
            _sunnyContext.SysOperLogs.RemoveRange(sysOperLogs);
            await _sunnyContext.SaveChangesAsync();
        }
    }
}